<?php

/**
 * 数据库操作类
 * author: 爱是西瓜
 * DateTime: 2018/5/01
 */

class Db{
    public static $conn;
    public static function conn(){

        if(!self::$conn){

            $type = 'mysql'; //数据库类型
            $db_name = 'mylink'; //数据库名
            $host = '127.0.0.1';
            $username = 'mylink';
            $password = 'ztlong2';

            $dsn = "$type:host=$host;dbname=$db_name";
            try {
                //建立持久化的PDO连接
                self::$conn = new PDO($dsn, $username, $password);
            } catch (Exception $e) {
                die('连接数据库失败!');
            }
        }

        return self::$conn;

    }

    public static function query($sql){
        echo $sql.PHP_EOL;
        return self::conn()->query($sql);
    }

    public static function exec($sql){
        return self::conn()->exec($sql);
    }

    public static function fetch($sql){
        $row = self::query($sql);
        return $row->fetch(PDO::FETCH_ASSOC);
    }

    public static function fetchAll($sql){
        $row = self::query($sql);
        return  $row->fetchAll(PDO::FETCH_ASSOC);
    }


    public static function find($table,$where,$field='*'){
        $sql = "SELECT {$field} FROM {$table} {$where} limit 1";
        return self::fetch($sql);
    }

    public static function select($table,$where,$field='*',$order='id desc'){
        $sql = "SELECT {$field} FROM {$table} {$where} order by {$order}";
        return self::fetchAll($sql);
    }

    public static function add($data,$table){
        $keys = implode(',',array_keys($data));
        $vals = "'".implode("','",$data)."'";
        $sql = "INSERT INTO {$table}({$keys}) VALUES({$vals});";
        return self::exec($sql);
    }

    public static function update($data,$table,$where){
        $setVal = [];
        foreach ($data as $k=>$v){
            $setVal[] = "{$k}='{$v}'";
        }

        $setVal = implode(',',$setVal);
        $sql = "UPDATE {$table} SET {$setVal} {$where};";
        echo $sql;
        return self::exec($sql);
    }


}
